package likou;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/07/14 16:45
 */
public class TreeUtil {

    private static TreeNode createTreeNode(Integer x) {
        if (x == null) {
            return null;
        }
        return new TreeNode(x);
    }

    public static TreeNode createTree(Integer[] integers) {
        if (integers.length == 0) {
            return null;
        }
        TreeNode res = new TreeNode(integers[0]);
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offerLast(res);
        int i = 1;
        while (i < integers.length) {
            TreeNode root = deque.pollFirst();
            if (root != null) {
                root.left = createTreeNode(integers[i]);
                deque.offerLast(root.left);
                i++;
                if (i == integers.length) {
                    break;
                }
                root.right = createTreeNode(integers[i]);
                deque.offerLast(root.right);
            } else if (integers[i] == null) {
                i++;
            } else if (integers[i] != null) {
                i--;
            }
            i++;
        }
        return res;
    }
}
